package core

import (
	"errors"
	"gopkg.in/yaml.v3"
	"os"
)

/* ============================================================ *
 * 功能:配置文件初始化
 * ============================================================ */

var globalConfig = make(map[string]interface{})

// 加载配置文件
func LoadGlobalConfigFile(path string) error {
	data, err := os.ReadFile(path)
	if err != nil {
		return err
	}

	// 把app.yaml中的配置内容 转换成 map
	if err = yaml.Unmarshal(data, &globalConfig); err != nil {
		return err
	}

	return nil
}

// 获取 组件配置 并 赋值到 conf 中
func GetCptConfig(name string, conf interface{}) error {
	if obj, ok := globalConfig[name]; ok {
		// 先 Marshal
		marshal, err := yaml.Marshal(obj)
		if err != nil {
			return err
		}
		// 后 Unmarshal 转两次?
		if err = yaml.Unmarshal(marshal, conf); err != nil {
			return err
		}
		return nil

	} else {
		return errors.New("the config[" + name + "] has not exists,please check!")
	}
}
